(function() {
    "use strict";
   /* $rootScope.confirm = function(url,msg,fn){
        var config = {btn: ['ok','cancel'],title:false};
        layer.confirm(msg,config,function(index){
            $http.get(url).success(function(data){
                fn&& fn(data);
                layer.close(index);
            });
        });
    }*/
    window.confirm = function(message,fn){
        layer.confirm(message, {btn: ['确定','取消'],title:false },function(index){ fn && fn();  layer.close(index);},function(){});
    }
    window.msg = function(tip){layer.msg(tip, {time: 2000, icon:1});}
    window.alert = function(tip){layer.msg(tip, {time: 2000, icon:5});}
    window.tips = function(tip,dom){var tipId = layer.tips(tip,dom,{ tips: [1,'#ff784e']}); $(dom).attr("tipId",tipId) };
    window.closeTip = function(dom){layer.close($(dom).attr("tipId")) };
    window.popOver = function(tip,dom){ layer.tips(tip,dom,{ tips: [1,'#444']}) };
    window.clickDownload = function(){
        var ss = "\ufeff";
        $(event.target).closest(".tab-pane").find("table.table tr").each(function(i,v){
            var cols = $("td,th", v).length;
            $.each($("td,th", v),function(i,td){
                if(i<cols && $(td).attr("excel")!="none") {
                    //ss+=$(td).html().stripTags().remove(/\s/g).replace(/,/g,'，').replace(/&nbsp;/g,' ')+",";
                    var content = $(td)[0].innerText.replace(/[\f\n\r\t\v]/g,"").replace(/,/g,"，");
                    if($(td).hasClass("bg-danger")){
                        content = "["+content+"]";
                    }
                    ss +=content+",";
                }
            });
            ss+="\n";
        })
       var title =  $("li.uib-tab.active > a").text();
        title = "网页数据"
        download(title+".csv",ss);
//	   str =  encodeURIComponent(ss);
//     $("#download")[0].href = "data:text/csv;charset=utf-8,"+str;
//     $("#download")[0].download=document.title+".csv";
//     $("#download")[0].click();
    }

    var app = angular.module("com.feng", ['ui.bootstrap']);

    app.directive('ensureUnique', ['$http', function($http) {
        return {
            require: 'ngModel',
            link: function(scope, ele, attrs, c) {
                scope.$watch(attrs.ngModel, function(v) {
                    if(!v){
                        return;
                    }
                    var pack ={id:attrs.id}
                    pack[attrs.ensureUnique] = v;
                    $http({
                        method: 'POST',
                        url: attrs.api,
                        params: pack
                    }).success(function(data, status, headers, cfg) {
                        c.$setValidity('unique', data.isUnique);
                    }).error(function(data, status, headers, cfg) {
                        c.$setValidity('unique', false);
                    });
                });
            }
        }
    }]);
    app.directive('order', function() {
        return {
            restrict : 'EA',
            //replace : true,
            transclude : true,
            scope : {},
            template : '<span class="sortbtn glyphicon glyphicon-sort" ng-if="!$parent.search.orderBy||!$parent.search.orderBy.startsWith(field)" ng-click="sortRet()"></span>'
                       +'<span class="sortbtn glyphicon glyphicon-sort-by-order" ng-if="$parent.search.orderBy==field+\' asc\'" ng-click="sortRet(\'desc\')"></span>'
                       +'<span class="sortbtn glyphicon glyphicon-sort-by-order-alt" ng-if="$parent.search.orderBy==field+\' desc\'" ng-click="sortRet(\'asc\')"></span>',
            link : function(scope, element, attrs) {
                scope.field = attrs.field;
                scope.sortRet = function(upOrdown) {
                    var orderBy = scope.field;
                    if(upOrdown == undefined){
                        orderBy+=" desc";
                    }else{
                        orderBy+=" "+upOrdown;
                    }
                    scope.$parent.search.orderBy =orderBy;
                    scope.$parent.find();
                }
            }
        }
    });

    //获取管理员account
    app.filter("idToValue",function(){
        return function(input,dictList){
            if(!input&& input!='0') return "";
            if(!angular.isArray(dictList)) return "";
            var objs = dictList.filter(function(n) {return n.id == input});
            return objs && objs[0].account;
        }
    });

    app.factory("dataService", function($http) {
        var postConfig = {
            transformRequest:function(obj){
                var str=[];
                if(typeof obj === 'object'&&!obj.length){
                    for(var p in obj){
                        str.push(encodeURIComponent(p) +"="+encodeURIComponent(obj[p]));
                    }
                }else if(typeof obj === 'object'&&obj.length>0){
                    for(var p in obj){
                        str.push(encodeURIComponent(obj[p].name) +"="+encodeURIComponent(obj[p].value));
                    }
                }
                return str.join("&");
            },
            headers:{'Content-Type':'application/x-www-form-urlencoded'}
        };

        return {
            postConfig:postConfig,
            //获取分页查询结果
            getPageResult:function(url,param,fn){
                $http.post(url,param).success(function(data, status, headers, config){
                    /**
                     * 始终得有第一页和最后一页.当前页 ,前一页,后一页.
                     */
                    var list =[1,data.currentPage-1,data.currentPage,data.currentPage+1,data.totalPage];
                    var pages = [];
                    var hash ={};
                    list.forEach(function(v){
                        if(!hash[v]&& v<=data.totalPage && v>0){
                            hash[v] =true;
                            pages.push(v);
                        }
                    })
                    if(pages.length>2&&pages.indexOf(2)==-1){
                        pages.splice(1,0,'······');
                    }
                    if(pages.length>2&&pages.indexOf(data.totalPage-1)==-1){
                        pages.splice(pages.length-1,0,'······');
                    }
                    data.pages = pages;
                    fn&&fn(data);
                }).error(function(data, status, headers, config) {
                    console.log("获取列表异常");
                });
            },


            // 本地导入
            upload: function(options,fn) {
                if(typeof(options.params)!="object"){
                    options.params = {};
                }
                if(!options.url){
                    options.url = '../common/uploadImg';
                }
                var index;
               if(options.nowait){
                   options.onSubmit = function(){};
               }else{
                   options.onSubmit = function(){
                       index = layer.load(1, {
                           shade: [0.2,'#000'] //0.1透明度的白色背景
                       });
                   };
               }
                options.onComplate = function(data) {
                    layer.close(index);
                    if(Array.isArray(data)){
                        fn&&fn(data);
                    }else if("object" == typeof data){
                        if(data.success){
                            fn&&fn(data);
                        }else{
                            layer.alert(data.error||"上传发生错误!",{btn: ['ok'],title:false});
                        }
                    }else{
                        layer.alert("发生错误:"+data,{btn: ['ok'],title:false});
                    }
                };
                // 上传方法
                $.upload(options);
            }
        }});

    app.controller('billCtl', function($scope,$http,$interval,$uibModal,dataService) {
        $scope.window = window;
        $scope.items = {};
        $scope.search = {};

        $scope.isAdmin = location.search.indexOf("?admin")==0?true:false;
        //获取管理员信息
        $scope.find = function(pageNo){
            $.extend($scope.search,{currentPage:pageNo||1,pageSize:$scope.items.pageSize||10});
            dataService.getPageResult("/bill/list",$scope.search,function(data){
                $scope.items = data;
            });
        };


        $scope.userPromist = $http.get("/adminUser/getUserbySession").then(function(resp){
            $scope.admin = resp.data;
            $scope.hasAccess = function(code){
                if($scope.admin.role.id ==1){
                    return true;
                }
                var menu = $scope.admin.role.menus[0];
                if(menu.access.indexOf(code)>-1){
                    return true;
                }else{
                    return false;
                }
            }
            return resp.data;
        })

        //获取相功能当前用户是否有权限


        $scope.userPromist.then(function(admin){
            $scope.find();
        })
        $scope.uploadExcel= function(){
            dataService.upload({url:"/bill/uploadExcel",params:{},
                accept:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"},function(resp){
                if(resp.success){
                    $scope.find();
                    $scope.wrongBills = resp.wrongBills;
                    $scope.statics = resp.statics;
                }else{
                    alert(data.error);
                }
            })
        }

        $scope.compareExcel= function(){
            dataService.upload({url:"/bill/compareExcel",params:{},nowait:true,
                accept:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"},function(resp){
                if(resp.success){
                    $scope.find();
                }else{
                    alert(data.error);
                }
            })
        }
        $scope.del = function(item){
            confirm("确定删除吗?",function(){
                $http.get("/bill/del/"+item.id).success(function(){
                    $scope.find();
                })
            })
        }

        $scope.edit = function(item){
            var copy = angular.extend({},item);
            item.copy = copy;
            item.edit = true;
        }

        $scope.save = function(form,item){
            form.$setSubmitted(true);
            if(!form.$valid){
                return;
            }
            $http.post("/bill/saveOrUpdate",item.copy).success(function(data, status, headers, config) {
                if(data.success){
                    msg("保存成功");
                    delete item.copy;
                    item.edit = false;
                    angular.extend(item,data.bill);
                } else {
                    alert(data.error);
                }
            })
        }
        $scope.cancel = function(item){
            if(item.id){
                delete item.copy;
                item.edit = false;
            }else{
                $scope.items.list.splice($scope.items.list.indexOf(item),1);
            }
        }
        $scope.addRec = function(){
            $scope.items.list.push({edit:true,copy:{}});
        }
        $scope.compare = function(bill){
            if(bill.showRec){
                bill.showRec = false;
            }else{
                bill.showRec = true;
                $http.get("/bill/getByInsuranceNo?insuranceNo="+bill.insuranceNo).success(function(data, status, headers, config) {
                    if(data.success){
                        bill.rec = data.bill;
                    } else {
                        alert(data.error);
                    }
                })
            }
        }
        $scope.truncate = function(){
            confirm("确定清空所有记录吗？请谨慎！",function(){
                $http.get("/bill/truncate").success(function(){
                    $scope.find();
                })
            })
        }

        $scope.bills = {};
        $scope.unFinished = [];
        $scope.uploadTotalBill = function(){
            dataService.upload({url:"/bill/uploadTotalBill",params:{},
                accept:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"},function(resp){
                $scope.bills.totalBillName = resp.name;
                $scope.$apply();
            })
        }
        $scope.uploadSubBill = function(){
            dataService.upload({url:"/bill/uploadSubBill",params:{},
                accept:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"},function(resp){
                $scope.bills.subBillName = resp.name;
                $scope.$apply();
            })
        }
        $scope.compareBills = function(){
            $http.get("/bill/getUploadedExcels").success(function(resp){
                $scope.bills = resp;
                if($scope.bills.subBillName && $scope.bills.totalBillName){
                    var elemIF = document.createElement("iframe");
                    elemIF.src = "/bill/compareBills";
                    elemIF.style.display = "none";
                    document.body.appendChild(elemIF);

                    var timer ;
                    var i =0;
                    var getUnFinished = function(){
                        $http.get("/bill/unFinished").success(function(resp){
                            $scope.unFinished = resp.unFinished||[];
                            if(resp.unFinished !=null){
                                $interval.cancel(timer);
                            }
                            console.error(++i);
                        });
                    }
                    timer = $interval(getUnFinished,1000,20 );
                }else{
                    alert("请上传帐单！");
                }
            })
        }

        $scope.showPasswordModal = function(){
            var modal = $uibModal.open({
                animation: false,
                size:'sm',
                templateUrl: '/modalPwd.html',
                controller: 'pwdCtrl'
            });
            modal.result.then(function () {
            }, function () {
                console.info('Modal dismissed at: ' + new Date());
            });
        }


        $http.get("/bill/getUploadedExcels").success(function(resp){
            $scope.bills = resp;
        })

        $http.get("/adminUser/findAllAdminUser").success(function(data, status, headers, config) {
           $scope.adminList = data;
        })

    });


    app.controller('pwdCtrl', function($scope,$http,$uibModalInstance,dataService) {

        $scope.ok = function(form){
            form.$setSubmitted(true);
            if(!$scope.form.$valid){
                return;
            }
            if($scope.password1!=$scope.password2){
                return ;
            }
            $http.post("/adminUser/changPwd",{password:$scope.password,password1:$scope.password1},dataService.postConfig).success(function(resp, status, headers, config) {
                if(resp.success){
                    layer.confirm("密码修改成功└(^o^)┘！请重新登陆。", {btn: ['确定'],title:false },function(index){ location.href="/login.html"; layer.close(index);});
                }else{
                    alert(resp.error);
                }
            })
        }

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

    })
    app.controller('wrongbillCtl', function($scope,$http,dataService) {
        $scope.search = {};
        $scope.find = function(pageNo){
            $.extend($scope.search,{currentPage:pageNo||1,pageSize:$scope.items.pageSize||10});
            dataService.getPageResult("/bill/listWrongBill",$scope.search,function(data){
                $scope.items = data;
            });
        };
        $scope.truncateWrong = function(){
            confirm("确定清空所有错误日志吗？请谨慎！",function(){
                $http.get("/bill/truncateWrong").success(function(){
                    $scope.find();
                })
            })
        }
        $scope.userPromist.then(function(admin){
            if(admin.role.id ==1 ||admin.role.id ==2){
                $scope.find();
            }
        })

        $scope.changeStatus = function(bill,status){
            $http.get("/bill/changeStatus",{params:{billId:bill.id,status:status}}).success(function(resp){
                if(resp.success){
                    bill.status = status;
                }
            })
        }

        $scope.del = function(item){
            confirm("确定删除吗?",function(){
                $http.get("/bill/delWrong/"+item.id).success(function(){
                    $scope.find();
                })
            })
        }


    })


})();